import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/modle/login/bloc/user_login_bloc.dart';
import 'package:shopping_group/modle/main/bloc/main_data_bloc.dart';
import 'package:shopping_group/modle/main/bloc/wxopenid_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/main/entity/id_name_entity.dart';
import 'package:shopping_group/modle/play/ui/wx_html_page.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/shared_preferences_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'details_page.dart';
import 'dart:js';
import 'package:bot_toast/bot_toast.dart';
import 'dart:convert' as convert;

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with AutomaticKeepAliveClientMixin {
  //listview的控制器
  ScrollController _scrollController = ScrollController();
  TextEditingController _controllerSreach = TextEditingController();
  List<IdNameEntity> _listType = [];
  List<String> _itmes = [];
  String _typeId = 'COMT_MUST_BUY';
  List<CommoSpec4AppRecordEntity> _list = [];
  Map<String, List<CommoSpec4AppRecordEntity>> _maplist = {};
  // StreamSubscription _typeSubscription;
  StreamSubscription _refresListSubscription;
  StreamSubscription _commSpecSubscription;
  StreamSubscription _wxCodeSubscription;
  StreamSubscription _wxOpenIdSubscription;
  MainDataBloc _bloc;
  UserLoginBloc _userLoginBloc;
  WxOpenIdBloc _wxOpenIdBloc;
  @override
  void initState() {
    super.initState();
    _initListener();
    _bloc = MainDataBloc();
    _bloc.initCommSpecData.add(_typeId);
    _userLoginBloc = UserLoginBloc();
    _wxOpenIdBloc = WxOpenIdBloc();
    _refresListSubscription = eventBus.on<RefreshEvent>().listen((event) {
      _pullToRefresh();
    });

    SharedPreferencesUtil.readShared('userEntity').then((entity) {
      if (null != entity && entity is String) {
        Map<String, dynamic> user = convert.jsonDecode(entity);
        _userLoginBloc.addUserAction.add(user);
      }
    });

    _itmes
      ..add(
          'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/commSpec/main_lbt1.png')
      ..add(
          'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/commSpec/main_lbt2.png');
  }

  _initListener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _bloc.moreDate.add(_scrollController);
      }
    });

    _wxOpenIdSubscription = eventBus.on<GetWxOpenIdEvent>().listen((event) {
      if (null != event) {
        _userLoginBloc.addUserAction.add(event.result);
        if (!ObjectUtil.isEmptyString(event.shopId)) {
          RouteUtil.goParameter(DetailsPage(id: event.shopId));
        }
      }
    });
    _wxCodeSubscription = eventBus.on<GetWxCodeUrlEvent>().listen((event) {
      if (null != event) {
        String codeUrl = event.codeUrl;
        context.callMethod('flutterRsetUrl', [codeUrl]);
      }
    });

    Future.delayed(Duration(milliseconds: 500), () {
      // BotToast.showText(text: 'isWeixin=' + isWeixin().toString());
      // context.callMethod(
      // var urlstr = context.callMethod(
      //     'flutterGetUrl'); //     'flutterAlert', ['weixinOperId=' + BaseConstant.weixinOperId]);
      // if ('dfk' == urlstr || 'order' == urlstr || 'fuGood' == urlstr) {
      //   return;
      // }
      if (Utils.isWeixin()) {
        if (ObjectUtil.isEmptyString(BaseConstant.weixinOperId)) {
          var type = context.callMethod('flutterGetType');

          if (null == type || ObjectUtil.isEmptyString(type.toString())) {
            var shopId = context.callMethod('flutterMethod');
            var phone = context.callMethod('flutterMethodPhone');
            BaseConstant.yaoqingrenPhone = phone ?? '';
            if (null != shopId &&
                shopId is String &&
                !ObjectUtil.isEmptyString(shopId)) {
              String url = Uri.encodeComponent(
                  '${Apis.WEB_URL}?type=reCodeUrl&phone=$phone&id=$shopId&');
              //   BotToast.showText(text: 'url=' + url);
              Map<String, dynamic> data = {};
              data['url'] = url;
              data['upcustphone'] = phone;
              _wxOpenIdBloc.codeDate.add(data);
            }
          } else if ('reCodeUrl' == type) {
            var shopId = context.callMethod('flutterMethod');
            var phone = context.callMethod('flutterMethodPhone');
            var code = context.callMethod('flutterWxCode');
            BaseConstant.yaoqingrenPhone = phone ?? '';
            if (null != code &&
                code is String &&
                !ObjectUtil.isEmptyString(code)) {
              Map<String, dynamic> data = {};
              data['code'] = code;
              data['shopId'] = shopId ?? '';
              data['upcustphone'] = phone ?? '';
              _wxOpenIdBloc.idDate.add(data);
            }
          }
          //  else if (!BaseConstant.isLogin) {
          //   String url = Uri.encodeComponent('${Apis.WEB_URL}?type=reCodeUrl&');
          //   Map<String, dynamic> data = {};
          //   data['url'] = url;
          //   data['upcustphone'] = '';
          //   _wxOpenIdBloc.codeDate.add(data);
          // }
        } else {
          flutterMethod();
          flutterMethodPhone();
        }
      } else {
        flutterMethod();
        flutterMethodPhone();
      }

      flutterReferrer();
      flutterGetReferrer();
      flutterGetType();
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "首页",
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colours.themeColor,
        centerTitle: true,
        elevation: 0,
      ),
      body: ListView(
        shrinkWrap: true,
        children: [
          Image.asset('images/1.png'),
          Container(
            height: 20,
          ),
          Image.asset('images/2.png'),
          Image.asset('images/5.png'),
          Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => TradeCenter()));
                    },
                    child: Image.asset('images/entrance1.png'),
                  ),
                ),
                Container(width: 16),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        onTap: () {
                          // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => MarkedOrderListPage()));
                        },
                        child: Image.asset(
                          'images/entrance2.png',
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                      Container(height: 16),
                      GestureDetector(
                        onTap: () {
                          // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => OrderListPage()));
                        },
                        child: Image.asset(
                          'images/entrance3.png',
                          fit: BoxFit.fitWidth,
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
              height: 114,
              child: GestureDetector(
                onTap: () {
                  // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => RentalListPage()));
                },
                child: Image.asset('images/4.png'),
              )),
          Image.asset('images/3.png'),
        ],
      ),
    );
  }

  Future _pullToRefresh() async {
    _maplist[_typeId]?.clear();
    _bloc.refreshDate.add(_typeId);
    return null;
  }

  //ListView的Item
  Widget buildItem(BuildContext context, int index) {
    return Container(
      // margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: GestureDetector(
          onTap: () {
            // if (!BaseConstant.isLogin) {
            //   RouteUtil.goView(PageConstance.LOGIN_PAGE);
            //   return;
            // }
            // BaseConstant.openShopId = _maplist[_typeId][index].id;
            // RouteUtil.goView(PageConstance.DETAILS_PAGE);
            RouteUtil.goParameter(DetailsPage(id: _maplist[_typeId][index].id));
          },
          child: _xunchaItem(_maplist[_typeId][index])),
    );
  }

  Widget _xunchaItem(CommoSpec4AppRecordEntity entity) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: 90.0,
              width: 90.0,
              margin: const EdgeInsets.all(2.0),
              child: FadeInImage.assetNetwork(
                image: entity.imgUrl,
                placeholder: 'images/picture_loading.png',
                fit: BoxFit.contain,
              ),
            ),
            flex: 2,
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  WidgetUtils.getTextMaxLinesView(
                      entity.name, Colours.text_2222, Dimens.FONT_SIZE_14,
                      maxLines: 3),
                  SizedBox(
                    height: Dimens.FONT_SIZE_16,
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 0),
                        child: Row(
                          children: <Widget>[
                            WidgetUtils.getTextColorView('¥${entity.outPrice}',
                                Colours.text_2222, Dimens.FONT_SIZE_16),
                            // SizedBox(
                            //   width: 4,
                            // ),
                            // WidgetUtils.getTextColorView('¥${entity.outPrice}',
                            //     Colours.gray_99, Dimens.FONT_SIZE_16,
                            //     decoration: TextDecoration.lineThrough,
                            //     decorationColor: Colours.gray_66),
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.only(top: 4),
                        child: WidgetUtils.getTextColorView(
                            '已售 ${entity.hadShopCt} 件',
                            Colours.text_2222,
                            Dimens.FONT_SIZE_12,
                            overflow: TextOverflow.clip),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            flex: 3,
          ),
        ],
      ),
    );
  }

  Widget buildGridView(IdNameEntity entity) {
    return GestureDetector(
      onTap: () {
        int count = _listType.length;
        for (var i = 0; i < count; i++) {
          _listType[i]
            ..color = Colours.yanqi_red
            ..radiusColor = Colours.transparent
            ..isSelect = false;
          entity
            ..color = Colours.title_white
            ..radiusColor = Colours.yanqi_red
            ..isSelect = true;
        }
        _bloc.initMainData.add(_listType);

        _typeId = entity.id;
        if (ObjectUtil.isEmptyList(_maplist[_typeId])) {
          _bloc.initCommSpecData.add(_typeId);
        } else {
          _bloc.initCommSpecData.add(_maplist[_typeId]);
        }
      },
      child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 8),
          color: Colours.transparent,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SizedBox(
                height: 2,
              ),
              // WidgetUtils.getTextColorView(
              //     entity.name, Colours.themeColor, Dimens.FONT_SIZE_16),
              // SizedBox(
              //   height: 8,
              // ),
              Container(
                decoration: BoxDecoration(
                    border: Border.all(
                        color: entity.isSelect
                            ? Colours.themeColor
                            : Colours.transparent,
                        width: 1.0),
                    borderRadius: BorderRadius.circular(15.0),
                    color: entity.isSelect
                        ? Colours.themeColor
                        : Colours.transparent),
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                child: Column(
                  children: <Widget>[
                    WidgetUtils.getTextColorView(
                        '${entity.name}',
                        entity.isSelect
                            ? Colours.title_white
                            : Colours.themeColor,
                        Dimens.FONT_SIZE_14),
                    // SizedBox(
                    //   height: 2,
                    // ),
                    // WidgetUtils.getTextColorView(
                    //     '专区',
                    //     entity.isSelect
                    //         ? Colours.title_white
                    //         : Colours.themeColor,
                    //     Dimens.FONT_SIZE_14),
                  ],
                ),
              ),
              SizedBox(
                height: 2,
              ),
            ],
          )),
    );
  }

  //flutter调用js
  void flutterMethod() {
    var shopId = context.callMethod('flutterMethod');
    if (!ObjectUtil.isEmptyString(shopId)) {
      // BotToast.showText(text: shopId);
      // if (!mounted) {
      RouteUtil.goParameter(DetailsPage(id: shopId));
      // }
    }
  }

  void flutterMethodPhone() {
    var phone = context.callMethod('flutterMethodPhone');
    BaseConstant.yaoqingrenPhone = phone;
    //BotToast.showText(text: 'Phone=' + BaseConstant.yaoqingrenPhone);
  }

  void flutterGetClientId() {
    var id = context.callMethod('get_client_id');
    BotToast.showText(text: 'id=' + id);
  }

  void flutterReferrer() {
    context.callMethod('flutterReferrer');
  }

  void flutterGetReferrer() {
    context.callMethod('flutterGetReferrer');
  }

  void flutterGetType() {
    var orderName = context.callMethod('flutterGetOrderName');
    var orderId = context.callMethod('flutterGetOrderId');
    var openType = context.callMethod('flutterGetOpenType');
    var type = context.callMethod('flutterGetType');
    if (!ObjectUtil.isEmptyString(BaseConstant.wxOrderId) &&
        BaseConstant.wxOrderId == orderId) {
      return;
    }
    BaseConstant.wxOrderId = orderId;
    if ('redirectUrl' == type &&
        !ObjectUtil.isEmptyString(orderName) &&
        !ObjectUtil.isEmptyString(orderId)) {
      RouteUtil.goParameter(WxHtmlPage(
          openType: openType, orderId: orderId, orderName: orderName));
    }
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    _controllerSreach?.clear();
    _wxCodeSubscription?.cancel();
    _wxOpenIdSubscription?.cancel();
    _refresListSubscription?.cancel();
    _commSpecSubscription?.cancel();
    super.dispose();
  }
}
